package org.sgmiller.quickstem;

import java.util.HashMap;

import static org.sgmiller.quickstem.TransactionState.*;

class RepeatableReadTransaction extends Transaction {

	RepeatableReadTransaction() {
		super(IsolationLevel.REPEATABLE_READ, true);
	}

	public RepeatableReadTransaction(long nestedTid) {
		super(IsolationLevel.REPEATABLE_READ, nestedTid, true);
	}

	HashMap<Stem<?>,Version<?>> repeatableReadLog=
		new HashMap<Stem<?>, Version<?>>();

	@Override
	protected Object consider(Stem<?> stem, Version<?> v)  {
		if (v.txn.isTopLevel() || isSubtransaction(v.txn)) {
			switch (v.txn.state.ordinal) {
			case ORD_OPEN:
				if (!isRelated(v.txn))
					break;
			case ORD_COMMITTED:
				//Its weird that this is inside the loop, but it saves an extra switch
				Version<?> vm=repeatableReadLog.get(stem);
				if (vm != null) {
					return vm.value;
				} else if (v.txn.tid <= tid) {
					repeatableReadLog.put(stem, v);
					return v.value;
				}	
				break;
			}
		}			
		return VAL_CONTINUE;
	}

	
}

